import { getType } from '@/library/libs/get-type'
import { isNil } from './is-valid'

export const { hasOwnProperty } = Object.prototype

export interface Target {
  [key: string | number]: any
}

/**
 * @description 浅拷贝
 * @param {object | array} source 源对象
 * @returns {object | array} 新对象
 */
export function shallowCopy(source: Target): Target {
  if (isNil(source) || typeof source !== 'object') return source
  const type = getType(source)
  if (type === 'object' || type === 'array') {
    const target: Target = source instanceof Array ? [] : {}
    for (const key in source) {
      if (hasOwnProperty.call(source, key)) {
        target[key] = source[key]
      }
    }
    return target
  }

  throw TypeError('Expect object or array')
}
